package com.wind.util;
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.aliyuncs.exceptions.ClientException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * SpeechSynthesizerDemo class
 *
 * 语音合成（TTS）Demo
 */
public class SpeechSynthesizerDemo {
    private String appKey;
    private String accessToken;
    NlsClient client;
    public SpeechSynthesizerDemo(String appKey, String token) {
        this.appKey = appKey;
        this.accessToken = token;
        // Step0 创建NlsClient实例,应用全局创建一个即可,默认服务地址为阿里云线上服务地址
        client = new NlsClient(accessToken);
    }
    private static SpeechSynthesizerListener getSynthesizerListener(String filePath) {
        SpeechSynthesizerListener listener = null;
        try {
            listener = new SpeechSynthesizerListener() {
                File f = new File(filePath);
                FileOutputStream fout = new FileOutputStream(f);
                // 语音合成结束
                @Override
                public void onComplete(SpeechSynthesizerResponse response) {
                    // 事件名称 SynthesisCompleted
                    System.out.println("name: " + response.getName() +
                            // 状态码 20000000 表示识别成功
                            ", status: " + response.getStatus() +
                            // 语音合成文件路径
                            ", output file :"+ f.getAbsolutePath()
                    );
                }
                // 语音合成的语音二进制数据
                @Override
                public void onMessage(ByteBuffer message) {
                    try {
                        byte[] bytesArray = new byte[message.remaining()];
                        message.get(bytesArray, 0, bytesArray.length);
                        System.out.println("write array:" + bytesArray.length);
                        fout.write(bytesArray);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }
    public void process(String TTSText,String filePath) {
        SpeechSynthesizer synthesizer = null;
        try {
            // Step1 创建实例,建立连接
            synthesizer = new SpeechSynthesizer(client, getSynthesizerListener(filePath));
            synthesizer.setAppKey(appKey);
            // 设置返回音频的编码格式
            synthesizer.setFormat(OutputFormatEnum.WAV);
            // 设置返回音频的采样率
//            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_8K);
            // 设置用于语音合成的文本
            synthesizer.setText(TTSText);
            // Step2 此方法将以上参数设置序列化为json发送给服务端,并等待服务端确认
            synthesizer.start();
            // Step3 等待语音合成结束
            synthesizer.waitForComplete();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            // Step4 关闭连接
            if (null != synthesizer) {
                synthesizer.close();
            }
        }
    }
    public void shutdown() {
        client.shutdown();
    }

    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @param
     * @return
     */
    public static String timeStamp2Date(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }

    public static String timeStamp(){
                 long time = System.currentTimeMillis();
                String t = String.valueOf(time/1000);
                return t;
            }
    public static void main(String[] args) throws ClientException {
//        if (args.length < 2) {
//            System.err.println("SpeechSynthesizerDemo need params: <app-key> <token>");
//            System.exit(-1);
//        }
        AccessToken accessToken = AccessToken.apply("LTAIWK6Wh88EE7gS", "gngFKXNSV2Lw3YQxahpBQH31wcdKEC");
        String token = accessToken.getToken();
        long expireTime = accessToken.getExpireTime();
        String t = String.valueOf(expireTime);
        String date = timeStamp2Date(t, "yyyy-MM-dd HH:mm:ss");

        String timeStamp = timeStamp();

        String datecc = timeStamp2Date(timeStamp, "yyyy-MM-dd HH:mm:ss");
        String appKey ="Lpdv5hwirssAfbwW" ;//= args[0];
//        String token = "115fbb541771412c887f858436337112";//"1414143bfb644857a614501a0b2342b8";//args[1];
        SpeechSynthesizerDemo demo = new SpeechSynthesizerDemo(appKey, token);
        demo.process("今天星期五  句号","D:\\app\\tts_test.wav");
        demo.shutdown();
    }
}